/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2016-11-07 10:32:47
 * @Description: 
 */

define(function(require, exports, module) {

    var share = {};

    share.placeholderImg = function() {
        return seajs.data.vars.base + '/resources/img/placeholder.png';
    };

    share.ajaxControl = function(obj) {
        var callback = obj.success;
        var errorCallback = obj.error;
        var success = function(data, status, xhr) {
            if (data.errcode == 100) {
                //share.loginOut();
                console.log('ajaxErrcode:100 session expiress!');
            } else if (data.errcode == 404) {
                console.log(data.errcode);
                return;
            } else {
                callback(data, status, xhr);
            }
        };
        obj.success = success;
        obj.timeout = 120000;
        obj.error = function(xhr, errorType, error) {
            console.log(xhr, errorType, error);
            share.limitTime();
            if (errorCallback) { errorCallback(xhr, errorType, error); }
        };
        obj.xhrFields = { withCredentials: true };
        return obj;
    };

    share.limitTime = function() {
        var currentTime = new Date().getTime();
        var prevTime = Util.getCookie('ajaxError_time') || 0;
        if (currentTime - prevTime > 20000) {
            share.error('alert', 'Oops! There was a problem connecting to the network. Please try again!');
            Util.setCookie('ajaxError_time', currentTime, { path: '/', domain: Util.rootDomain(domain) });
        }
    };

    //type console.log/alert
    share.error = function(type, msg, obj) {
        if (type == 'console') {
            console.log(msg);
        } else {
            alert(msg);
        }
    };

    share.accessPermission = function() {
        var bool = false,
            nmmid = Util.getCookie('client_key');

        share.setProfileOptions();

        if (Util.queryString('mock')) {
            nmmid = Util.queryString('sid');
        }

        if (nmmid) {
            bool = true;
        }
        return bool;
    };

    share.checkPermission = function(callback) {
        var bool = this.accessPermission(),
            userInfo = this.getUserInfo();
        if (bool) {
            if (!userInfo) {
                share.pageLoad(true);
                share.resetLogin(callback);
            } else {
                share.renderPage(callback);
            }
        } else {
            share.browserClear();
            console.log('accessPermission error, will goto index.html');
            //share.gotoUrl('./index.html');
        }
        return false;
    };

    share.browserClear = function() {
        if (location.href.indexOf("?dev")) {
            Util.delCookie('client_key', { path: '/', expires: -1, domain: Util.rootDomain(domain) });
            Util.delCookie('session_id', { path: '/', expires: -1, domain: Util.rootDomain(domain) });
        }
        sessionStorage.clear();
        localStorage.clear();
    };

    share.removeLocalStorage = function(key) {
        util.removeLocalStorage(key);
    };

    share.resetLogin = function(callback) {

        var url,
            mock = Util.queryString('mock'),
            sid = Util.queryString('sid');

        if (mock) {
            url = seajs.data.vars.apiUrl + 's' + sid + '/login';
        } else {
            url = seajs.data.vars.apiUrl + 'login';
        }

        var ajaxObj = {
            url: url,
            type: 'GET',
            //async: false,
            success: function(data) {
                if (typeof(data.errcode) == 'undefined') {
                    share.loginSuccess(data, callback);
                } else {
                    share.browserClear();
                }
            },
            error: function(xhr, errorType, error) {
                share.error('alert', 'error');
            }
        };
        $.ajax(share.ajaxControl(ajaxObj));
    };

    share.getUserInfo = function() {
        var data = Util.getSessionStorage("userInfo");
        if (data) {
            data = JSON.parse(data);
        }
        return data;
    };

    share.gotoUrl = function(url, type) {
        if (type) {
            window.open(url);
        } else {
            window.location.href = url;
        }
    };

    share.loginSuccess = function(data, callback) {
        console.log('loginSuccess', data);
        if (location.href.indexOf("?dev") > 0) {
            Util.setCookie('client_key', Util.md5(new Date().getTime()), { path: '/', domain: Util.rootDomain(domain) });
            Util.setCookie('session_id', data.session_id, { path: '/', domain: Util.rootDomain(domain) });
        } else if (Util.queryString('mock')) {
            if (!Util.getCookie('client_key')) {
                Util.setCookie('client_key', Util.md5(new Date().getTime()), { path: '/', domain: Util.rootDomain(domain) });
                Util.setCookie('session_id', data.session_id, { path: '/', domain: Util.rootDomain(domain) });
            }
        }
        if (data['session_id']) { delete data['session_id']; }
        Util.setSessionStorage("userInfo", JSON.stringify(data));
        if (callback) {
            this.getUserStatus(callback);
        }
    };

    share.pageLoad = function(bool) {
        var html = '<div id="pageLoad">' +
            '<div class="des"></div>' +
            '<div class="spinner"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div></div>' +
            '</div>';
        if (bool) {
            if ($('#pageLoad').length < 1) {
                $('body').append(html);
            }
        } else {
            $('#pageLoad').remove();
        }
    };

    share.renderPage = function(callback) {
        share.pageLoad(false);
        if (callback) {
            callback();
        }
    };

    share.repalceTpl = function(str, arr) {
        //str = 'aaa$0bbb$1ccc';
        var patten = new RegExp("\\$\\d{1}", "g"),
            newStr = str.replace(patten, function(value) {
                var index = parseInt(value.replace('$', ''));
                return arr[index];
            });
        return newStr;
    };

    share.listenLocalStorage = function() {
        var func = function(e) {
            if (e.key == 'ms_load_time') {
                //console.log('otherPage', new Date().toString());
                Util.syncSessionStore();
            } else if (e.key == 'pushSessionStorage' && e.newValue) {
                var data = JSON.parse(e.newValue),
                    type = data.type,
                    sourceDate = data.source;
                for (key in sourceDate) {
                    Util.setSessionStorage(key, sourceDate[key], true);
                }
                //console.log('receive', new Date().toString());
                /*
                if (type !== 'sessionStroage') {
                    console.log(type, sourceDate);
                }
                */
            }
        };
        //$(window).on('storage', function(e) {
        if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
            window.attachEvent("storage", func);
        } else {
            window.addEventListener("storage", func);
        }
        Share.pullSessionStorage();
    };

    share.pullSessionStorage = function() {
        //console.log('pull', new Date().toString());
        Util.setLocalStorage('ms_load_time', JSON.stringify({ value: Date.now(), label: "time" }));
        //Util.setLocalStorage('ms_load_time', Date.now());
    };

    share.setProfileOptions = function(callback) {
        var data = localStorage.getItem("ms_gender");
        if (data == null || data == '') {
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'get_profile_options',
                type: 'GET',
                async: false,
                success: function(data) {
                    if (data.results == 1) {
                        for (var item in data.data) {
                            Util.setLocalStorage("ms_" + item, JSON.stringify(data.data[item]));
                        }
                        if (callback) { callback() }
                    }
                }
            };
            $.ajax(share.ajaxControl(ajaxObj));
        }
    };

    share.updateProfile = function(userInfo, callback) {
        var obj = {
            //url : seajs.data.vars.apiAccessUrl+'save_profile',
            url: seajs.data.vars.apiAccessUrl + 'update_profile',
            type: 'POST',
            data: userInfo,
            success: function(data) {
                if (data.errcode) {
                    alert(data.errmsg);
                } else if (data.errs) {
                    alert(data.errs[0].errmsg);
                } else {
                    if (callback) {
                        callback(data);
                    }
                }
            }
        };
        $.ajax(share.ajaxControl(obj));
    };

    share.getUserStatus = function(callback) {
        if (!Util.getSessionStorage('userStatus')) {
            var ajaxObj = {
                url: seajs.data.vars.apiUrl + 'status_bar_data',
                type: 'GET',
                success: function(data) {
                    if (data) {
                        Util.setSessionStorage('userStatus', JSON.stringify(data));
                        share.renderPage(callback);
                    }
                }
            };
            $.ajax(Share.ajaxControl(ajaxObj));
        } else {
            callback();
        }
    };

    /*
    share.synchData = function() {
        Util.setLocalStorage('pushSessionStorage', JSON.stringify({ type: 'sessionStroage', source: sessionStorage }));
        Util.removeLocalStorage('pushSessionStorage');
    };
   
    share.syncUserStatus = function(userStatus) {
        if (userStatus) {
            Util.setSessionStorage('userStatus', JSON.stringify(userStatus));
        }
        Util.setLocalStorage('pushSessionStorage', JSON.stringify({ type: 'userStatus', source: sessionStorage }));
        Util.removeLocalStorage('pushSessionStorage');
    };

    share.syncUserInfo = function(userInfo) {
        if (userInfo) {
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
        }
        Util.setLocalStorage('pushSessionStorage', JSON.stringify({ type: 'userInfo', source: source: sessionStorage }));
        Util.removeLocalStorage('pushSessionStorage');
    };
    */

    share.getMonthStr = function(val) {
        var monthName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            monthHtml = '';
        for (i = 0; i < 12; i++) {
            monthHtml += '<option ' + (typeof(val) != 'undefined' && parseInt(val) == (i + 1) ? 'selected' : '') + ' value="' + (i + 1) + '">' + monthName[i] + '</option>';
        }
        return monthHtml;
    }

    share.getDayStr = function(year, month, val) {
        var dayHtml = '';
        for (i = 1; i < (new Date(year, month, 0).getDate() + 1); i++) {
            dayHtml += '<option ' + ((typeof(val) != 'undefined' && parseInt(val) == i) ? 'selected' : '') + ' value="' + i + '">' + i + '</option>';
        }
        return dayHtml;
    }

    share.getYearStr = function(starYear, endYear, val) {
        var yearHtml = '';
        for (i = starYear; i < (endYear + 1); i++) {
            yearHtml += '<option ' + (typeof(val) != 'undefined' && parseInt(val) == i ? 'selected' : '') + ' value="' + i + '">' + i + '</option>';
        }
        return yearHtml;
    }

    share.getMatchAgeStr = function(val) {
        var matchAgeHtml = '';
        for (i = 1; i < 100; i++) {
            matchAgeHtml += '<option ' + (typeof(val) != 'undefined' && parseInt(val) == i ? 'selected' : '') + ' value="' + i + '">' + i + '</option>';
        }
        return matchAgeHtml;
    }

    share.getSelectLabel = function(mid, value, defaultStr, noValueStyle) {
        var select = share.getLocalStorage(mid);
        for (var i in select) {
            if (select[i].value == value) {
                return select[i].label;
            }
        }
        var str = defaultStr || Lang.askMe;
        if (typeof(noValueStyle) != 'undefined') {
            str = '<span class="' + noValueStyle + '">' + str + '</span>';
        }
        return str;
    }

    share.getCheckboxLabel = function(mid, val, spe, defaultStr, noValueStyle) {
        var str = share.getCheckboxStr(mid, val, spe);
        var strs = str || defaultStr || Lang.askMe;
        if (typeof(noValueStyle) != 'undefined' && $.trim(str).length == 0) {
            strs = '<span class="' + noValueStyle + '">' + strs + '</span>';
        }
        return strs;
    };

    share.getCheckboxStr = function(mid, val, spe, len) {
        var arr = [],
            select = share.getLocalStorage(mid);
        var str = '',
            spe = spe ? spe : '</br>';
        if (select.length > 0) {
            for (var i in select) {
                if (parseInt(parseInt(val) & parseInt(select[i].value)) > 0) {
                    arr.push(select[i].label);
                }
            }
            str = arr.join(spe);
            if (len) {
                str = util.subString(str, len);
            }
        }
        return str;
    };

    share.getCheckboxHtml = function(mid, val, itemName) {
        var select = share.getLocalStorage(mid),
            html = '';
        for (i = 0; i < select.length; i++) {

            if (parseInt(parseInt(val) & parseInt(select[i].value)) > 0) {
                html += '<dd><input value=' + select[i].value + ' name="' + itemName + '" type="checkbox" checked /> ' + select[i].label + '</dd>';
            } else {
                html += '<dd><input value=' + select[i].value + ' name="' + itemName + '" type="checkbox" /> ' + select[i].label + '</dd>';
            }
        }
        return html;
    };

    share.getSelectHtml = function(mid, val) {
        var select = share.getLocalStorage(mid),
            html = '';
        for (i = 0; i < select.length; i++) {
            if (typeof(val) != 'undefined' && $.trim(val).toString() == $.trim(select[i].value).toString()) {
                html += '<option selected value=' + select[i].value + '>' + select[i].label + '</option>';
            } else {
                html += '<option value=' + select[i].value + '>' + select[i].label + '</option>';
            }
        }
        return html;
    };

    share.getSelectGroupLabel = function(mid, value, defaultStr, noValueStyle) {
        var select = share.getLocalStorage(mid);
        for (var i in select) {
            var list = select[i].list;
            for (var j in list) {
                if (list[j].value == value) {
                    return list[j].label;
                }
            }
        }
        var str = defaultStr || Lang.askMe;
        if (typeof(noValueStyle) != 'undefined') {
            str = '<span class="' + noValueStyle + '">' + str + '</span>';
        }
        return str;
    }

    share.getSelectGroupHtml = function(mid, val, defaultOption) {
        var select = share.getLocalStorage(mid),
            html = defaultOption ? '<option value="">' + defaultOption + '</option>' : '';
        for (i = 0; i < select.length; i++) {
            html += '<optgroup label="' + select[i].label + '">';
            var list = select[i].list;
            for (var j = 0; j < list.length; j++) {
                if (typeof(val) != 'undefined' && $.trim(val).toString() == $.trim(list[j].value).toString()) {
                    html += '<option selected value=' + list[j].value + '>' + list[j].label + '</option>';
                } else {
                    html += '<option value=' + list[j].value + '>' + list[j].label + '</option>';
                }
            }
            html += '</optgroup>';
        }
        return html;
    };

    share.getCheckboxData = function(arr) {
        var val = 0;
        $.each(arr, function(index, value) {
            if ($(this).is(':checked')) {
                val += parseInt($(this).val());
            }
        });
        return val;
    };

    share.getLocalStorage = function(key) {
        var data = JSON.parse(localStorage.getItem(key));
        if (data == null || data == undefined || data == '') {
            this.setProfileOptions({
                async: 0
            });
            data = JSON.parse(localStorage.getItem(key));
        }
        return data;
    };

    share.getStorage = function(key) {
        return sessionStorage.getItem(key);
    };

    share.ajaxStartB = function(dom, bool) {
        var html = $("<div class='listLoading'></div>");
        if (dom.find('.listLoading').length < 1) {
            if (bool) {
                dom.prepend(html);
            } else {
                dom.append(html);
            }
        }
    };

    share.ajaxEndB = function(dom) {
        dom.find('.listLoading').remove();
    };

    module.exports = share;
});
